package vn.ducquoc.util.schedule;

public class TimerExample {

  public static void main(String[] args) {
    java.util.Timer timer = new java.util.Timer();

    schedule(timer);

    scheduleAtFixedRate(timer);
  }

  private static void schedule(java.util.Timer timer) {
    final long millisecondsDelay = 2000;
    java.util.Date timeToRun = new java.util.Date(System.currentTimeMillis()
            + millisecondsDelay);

    System.out.println("Schedule: " + millisecondsDelay / 1000 + "s delay");
    timer.schedule(new java.util.TimerTask() {
      public void run() {
        System.out.println("schedule() : run at a certain time");
      }
    }, timeToRun);
  }

  private static void scheduleAtFixedRate(java.util.Timer timer) {
    final long delay = 4000;
    final long period = 1000;

    System.out.println("Schedule at fixed rate: " + delay / 1000 + "s delay");
    timer.scheduleAtFixedRate(new java.util.TimerTask() {
      public void run() {
        System.out.println("scheduleAtFixedRate() : repeated " + period / 1000
                + "s interval");
      }
    }, delay, period);
  }

}
